package com.changgou.order.service.impl;

import com.changgou.common.constant.OrderContant;
import com.changgou.common.vo.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private SkuFeign skuFeign;

    /**
     * 将商品及购买数量加入到当前登录用户对应的购物车中
     *
     * @param id  商品id sku id
     * @param num 加入购物车数量
     * @return 操作结果
     */
    @Override
    public void add(Long id, Integer num,String username) {
        //根据sku id查询sku；
        Result<Sku> skuResult = skuFeign.findById(id);

        if (skuResult.getData()!=null){
            //根据spu id 查询spu
            Result<Spu> spuResult = spuFeign.findById(skuResult.getData().getSpuId());

            //根据sku 和 spu 及购买数量构造orderItem
            OrderItem orderItem= createOrderItem(skuResult.getData(),spuResult.getData(),num);

            //将orderItem存入redis
            redisTemplate.boundHashOps(OrderContant.CART_PREFIX+username).put(num,orderItem);
        }


    }

    /**
     * 查询当前登录用户的购物车列表
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        return redisTemplate.boundHashOps(OrderContant.CART_PREFIX+username).values();
    }

    /**
    * 创建订单明细对象
    * @param sku 商品sku
    * @param spu 商品spu
    * @param num 购买数量
    * @return 订单明细
    */
    private OrderItem createOrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem=new OrderItem();
        orderItem.setSkuId(sku.getId());
        orderItem.setNum(num);
        orderItem.setPrice(sku.getPrice());
        //要购买多个个商品*单个商品重量
        orderItem.setWeight(sku.getWeight()*num);
        //支付金额 = 单价*数量
        orderItem.setMoney(orderItem.getPrice()*num);
        orderItem.setPayMoney(orderItem.getMoney());
        //不是回退商品
        orderItem.setIsReturn("0");
        orderItem.setImage(sku.getImage());
        orderItem.setName(sku.getName());

        orderItem.setSpuId(spu.getId());
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        return orderItem;
    }
}
